<?php

namespace app\api\controller;


use app\admin\model\Notifylog;
use app\common\controller\Api;
use addons\epay\library\Service;
use Exception;
use think\Db;
use app\common\model\User;
use app\admin\model\Order;
use app\admin\model\Userticket;
class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function __construct()
    {
        parent::__construct();
    }
    public function notify(){
        //支付回调
            $postData = file_get_contents('php://input');
            Notifylog::insert(['detail' => $postData,'time' => time()]);
            $pay = Service::checkNotify('wechat');
            if (!$pay) {
                return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
            }

            // 获取回调数据，V3和V2的回调接收不同
            $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

            try {
                //微信支付V3返回和V2不同
                if (Service::isVersionV3() ) {
                    $data = $data['resource']['ciphertext'];
                    $data['total_fee'] = $data['amount']['total'];
                }

                \think\Log::record($data);
                //获取支付金额、订单号
                $payamount = $data['total_fee'] / 100;
                $out_trade_no = $data['out_trade_no'];
                $prefix = substr($out_trade_no, 0, 2);
              
                $type = 0;
                if($prefix == 'PD') {
                    $type = 1;
                }

                //如果是水票的
                if($type == 0) {
                     $detail =   Userticket::where('order_id',$out_trade_no)->find();
                     if($detail) {
                        //1.修改订单状态
                        $detail->status = 1;
                        $detail->pay_money = $payamount;
                        $detail->pay_time = time(); 
                        $detail->save();
                        User::getScoreAndWater($detail->user_id,$payamount);//二级分销
                        Db::name('user_ticket_record')->where('ticket_id',$detail['id'])->update(['status' => 1,'pay_time' => time()]);
                        Db::name('ticket')->where('id',$detail['ticket_id'])->dec('num',$detail->num);
                     }
                }
                if($type == 1) {//如果是购买水的
                    $detail =  Order::where('order_id',$out_trade_no)->find();
                    if($detail['status'] != 0) {//如果状态不是0 ，证明已经处理过了
                        return ;
                    } 
                    if($detail) {
                        $detail->status = 1;
                        $detail->pay_money = $payamount;
                        $detail->pay_time = time(); 
                        $detail->save();
                        Db::name('order_detail')->where('order_sn',$out_trade_no)->update(['status' =>1,'pay_time' => time()]);
                        if($detail->source != 2) {
                            User::getScoreAndWater($detail->user_id,$payamount);//二级分销
                        }
                       
                        if($detail->bucket == 0) {//押金桶，如果有
                            User::addBucket($detail->user_id);
                        }
                        if($detail->source == 1) {//如果从购物车购买的，要清空购物车
                            User::dealCarList($detail->detail_id,$detail->user_id);
                        }
                        if($detail->luck_id) {//如果抽奖获得的，
                            Db::name('luck')->where(['id' =>$detail->luck_id])->update(['status' => 2]);
                        }
                        //减去库存数量
                        User::decNum($out_trade_no);
                        //如果有使用水票
                        User::dealTicket($detail->ticket_ids,$detail->user_id);
                       
                    }
                }

                //你可以在此编写订单逻辑
            } catch (Exception $e) {
                \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
            }
            //下面这句必须要执行,且在此之前不能有任何输出
            if (Service::isVersionV3()) {
                return $pay->success()->getBody()->getContents();
            } else {
                return $pay->success()->send();
            }
    }
    /**
     * 
     * 提现回调
     * @return void
     */
    public function withdrawNotify()
    {
        $postData = file_get_contents('php://input');
        Notifylog::insert(['detail' => $postData,'time' => time(),'type' => 1]);
    }
}